import { Common } from '../../utils/common.js';
var common = new Common();

var Moment = require("../../utils/moment.js");
var DATE_LIST = [];
var DATE_YEAR = new Date().getFullYear();
var DATE_MONTH = new Date().getMonth() + 1;
var DATE_DAY = new Date().getDate();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tour_info: "",
    show: false,
    year: new Date().getFullYear(), // 年份
    month: new Date().getMonth() + 1, // 月份
    day: new Date().getDate(), // 日期

    checkInDate: Moment(new Date()).format('YYYY-MM-DD'),
    checkOutDate: Moment(new Date()).add(1, 'day').format('YYYY-MM-DD'),
    dateList: [],
    markcheckInDate: false, //标记开始时间是否已经选择
    markcheckOutDate: false, //标记结束时间是否已经选择
    maxMonth: 7, //最多渲染月数

    header: true, // 日历标题
    lunar: false, // 显示农历
    more: false, // 显示非当前月日期                
    week_title: true, // 显示周标题
    next: true, // 显示下个月
    prev: true, // 显示上个月
    show_calendar: false,

    cs: 30, // 单元格大小
    title_type: 'cn', // 周标题类型
    titleType: ['中文简写'],
    title_index: 0,
    style: [],
    activeType: 'square', // 日期背景效果
    days_addon: []
  },
  onClose() {
    this.setData({
      show_calendar: false
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.info) {
      var tour_info = JSON.parse(options.info);
      this.setData({
        tour_info: tour_info,
        show: true
      })
    }

    const today = new Date();
    const last_date = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    const days_count = last_date.getDate();
    this.createDateListData();
  },
  /*
   * 获取月的总天数
   */
  getTotalDayByMonth: function(year, month) {
    month = parseInt(month, 10);
    var d = new Date(year, month, 0);
    return d.getDate();
  },
  /*
   * 获取月的第一天是星期几
   */
  getWeek: function(year, month, day) {
    var d = new Date(year, month - 1, day);
    return d.getDay();
  },
  createDateListData: function() {
    var dateList = [];
    var now = new Date();
    /*
      设置日期为 年-月-01,否则可能会出现跨月的问题
      比如：2017-01-31为now ,月份直接+1（now.setMonth(now.getMonth()+1)），则会直接跳到跳到2017-03-03月份.
        原因是由于2月份没有31号，顺推下去变成了了03-03
    */
    now = new Date(now.getFullYear(), now.getMonth(), 1);
    for (var i = 0; i < this.data.maxMonth; i++) {
      var momentDate = Moment(now).add(this.data.maxMonth - (this.data.maxMonth - i), 'month').date;
      var year = momentDate.getFullYear();
      var month = momentDate.getMonth() + 1;

      var days = [];
      var totalDay = this.getTotalDayByMonth(year, month);
      var week = this.getWeek(year, month, 1);
      //-week是为了使当月第一天的日期可以正确的显示到对应的周几位置上，比如星期三(week = 2)，
      //则当月的1号是从列的第三个位置开始渲染的，前面会占用-2，-1，0的位置,从1开正常渲染
      for (var j = -week + 1; j <= totalDay; j++) {
        var tempWeek = -1;
        if (j > 0)
          tempWeek = this.getWeek(year, month, j);
        var clazz = '';
        if (tempWeek == 0 || tempWeek == 6)
          clazz = 'week'
        if (j < DATE_DAY && year == DATE_YEAR && month == DATE_MONTH)
          //当天之前的日期不可用
          clazz = 'unavailable ' + clazz;
        else
          clazz = '' + clazz
        days.push({
          day: j,
          class: clazz
        })
      }
      var dateItem = {
        id: year + '-' + month,
        year: year,
        month: month,
        days: days
      }

      dateList.push(dateItem);
    }
    // var sFtv = this.data.sFtv;
    // for (let i = 0; i < dateList.length; i++) {//加入公历节日
    //   for (let k = 0; k < sFtv.length; k++) {
    //     if (dateList[i].month == sFtv[k].month) {
    //       let days = dateList[i].days;
    //       for (let j = 0; j < days.length; j++) {
    //         if (days[j].day == sFtv[k].day) {
    //           days[j].daytext = sFtv[k].name
    //         }
    //       }
    //     }
    //   }
    // }
    this.setData({
      dateList: dateList
    });
    DATE_LIST = dateList;
  },
  resignFocus: function(e) {
    this.setData({
      show: true,
      tour_title: e.detail.value
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  //保存行程
  formSubmit: function(e) {
    var title = this.data.tour_title;
    var start_time = this.data.start_time;
    var end_time = this.data.end_time;
  
    if (title == undefined || start_time == undefined || end_time == undefined) {
      wx.showToast({
        title: '请填写正确信息',
        icon: 'none', // 'none'为无图标
        duration: 2000, //多少毫秒后消失      
      });
    } else {
      var data = {
        id: '',
        title: title,
        start_time: start_time,
        end_time: end_time
      };
      var datas = {
        data:data,
        type:'post',
        url:'scheduling'
      }
      common.DataToCallBack(datas, data => {
        if (data.code == 201) {
          //提示成功 跳转
          wx.showToast({
            title: '成功',
            icon: 'success', // 'none'为无图标
            duration: 2000, //多少毫秒后消失      
          });
          wx.navigateBack({
            delta: 1
          });
        } 
        else {
          var e_title = "行程安排有误";
          var key = '';
          for (var key in data.msg) {
            key = key;
            break;
          }
          if (key)
            e_title = data.msg[key];
          //提示失败
          wx.showToast({
            title: e_title,
            icon: 'none', // 'none'为无图标
            duration: 2000 //多少毫秒后消失
          });
        }
      })
    }
  },

  choose_date: function() {
    var show_calendar = this.data.show_calendar
    this.setData({
      show_calendar: !show_calendar
    })
  },
  addYear: function() {
    this.setData({
      year: this.data.year + 1
    });
  },

  subYear: function() {
    this.setData({
      year: this.data.year - 1
    });
  },

  addMonth: function() {
    if (this.data.month == 12) {
      this.setData({
        month: 1,
        year: this.data.year + 1
      });
    } else {
      this.setData({
        month: this.data.month + 1
      });
    }
  },

  subMonth: function() {
    if (this.data.month == 1) {
      this.setData({
        month: 12,
        year: this.data.year - 1
      });
    } else {
      this.setData({
        month: this.data.month - 1
      });
    }
  },

  switchMore: function() {
    this.setData({
      more: !this.data.more
    });
  },

  switchHeader: function() {
    this.setData({
      header: !this.data.header
    });
  },

  switchLunar: function() {
    if (this.data.lunar) {
      this.setData({
        lunar: !this.data.lunar,
        cs: 30
      });
    } else {
      this.setData({
        lunar: !this.data.lunar,
        cs: 50
      });
    }
  },

  switchNext: function() {
    this.setData({
      next: !this.data.next
    });
  },

  switchPrev: function() {
    this.setData({
      prev: !this.data.prev
    });
  },


  changeTitle: function(event) {
    const index = event.detail.value;
    switch (index) {
      case '0':
        this.setData({
          title_index: index,
          title_type: 'cn'
        });
        break;
      case '1':
        this.setData({
          title_index: index,
          title_type: 'cn'
        });
        break;
      case '2':
        this.setData({
          title_index: index,
          title_type: 'cn'
        });
        break;
      case '3':
        this.setData({
          title_index: index,
          title_type: 'cn'
        });
        break;
    }

  },

  switchTitle: function() {
    this.setData({
      week_title: !this.data.week_title
    });
  },

  changeCellSize: function(event) {
    this.setData({
      cs: event.detail.value
    });
  },

  changeActiveType: function(event) {
    this.setData({
      activeType: event.detail.value
    });
  },

  /**
   * 点击下个月
   */
  nextMonth: function(event) {
    const currentYear = event.detail.currentYear;
    const currentMonth = event.detail.currentMonth;
    const prevMonth = event.detail.prevMonth;
    const prevYear = event.detail.prevYear;
  },

  /**
   * 点击上个月
   */
  prevMonth: function(event) {

    const currentYear = event.detail.currentYear;
    const currentMonth = event.detail.currentMonth;
    const prevMonth = event.detail.prevMonth;
    const prevYear = event.detail.prevYear;
  },

  /**
   * 日期变更事件
   */
  dateChange: function(event) {
    const currentYear = event.detail.currentYear;
    const currentMonth = event.detail.currentMonth;
    const prevMonth = event.detail.prevMonth;
    const prevYear = event.detail.prevYear;
  },
  Todo: function(startDate, endDate) {
    var ab = startDate.split("-");
    var ae = endDate.split("-");
    var db = new Date();
    db.setFullYear(ab[0], ab[1] - 1, ab[2]);
    var de = new Date();
    de.setFullYear(ae[0], ae[1] - 1, ae[2]);
    var a = [];
    for (var i = 0, temp = db; temp < de; i++) {
      a[i] = this.GetDate(temp);
      temp.setTime(temp.getTime() + 24 * 60 * 60 * 1000);
    }
    a[i] = this.GetDate(de);
    return a.join();
  },
  GetDate: function(d) {
    var month;
    var dateDay;
    var yue = d.getMonth() + 1;
    var day = d.getDate();
    if (yue <= 9) {

      month = "0" + yue;

    } else {
      month = yue;
    }

    if (day <= 9) {
      dateDay = "0" + day;
    } else {
      dateDay = day;
    }
    return d.getFullYear() + "-" + month + "-" + dateDay;
  },
  dayClick: function(event) {
    const year = event.detail.year;
    const month = event.detail.month;
    const day = event.detail.day;
    const color = event.detail.color;
    const lunarMonth = event.detail.lunarMonth;
    const lunarDay = event.detail.lunarDay;
    const background = event.detail.background;

    var old_year = this.data.old_year;
    var old_month = this.data.old_month;
    var old_day = this.data.old_day;
    if (old_year == undefined || old_month == undefined || old_day == undefined) {
      this.setData({
        old_year: year,
        old_month: month,
        old_day: day
      })
    } else {
      if (year < old_year) {
        this.setData({
          old_year: year,
          old_month: month,
          old_day: day
        })
      } else if (year == old_year) {
        if (month < old_month) {
          this.setData({
            old_month: month,
            old_day: day
          })
        } else if (month == old_month) {
          if (day < old_day) {
            this.setData({
              old_day: day
            })
          }
        }
      }
    }

    var startDate = this.data.old_year + "-" + this.data.old_month + "-" + this.data.old_day;
    var endDate = year + "-" + month + "-" + day;
    var during_date = this.Todo(startDate, endDate);
    var ab = during_date.split(",");
    var style = [];
    for (var i = 0; i < ab.length; i++) {
      var cd = ab[i].split("-");
      var style_year = cd[0];
      var style_month = cd[1];
      var style_day = cd[2];
      if (i == 0 || i == ab.length - 1) {
        var style_tem = {
          year: "",
          month: "",
          day: "",
          color: "white",
          background: "#0076CD"
        };
        if (i == 0) {
          var start_time = cd;
        } else {
          var end_time = cd;
        }
      } else {
        var style_tem = {
          year: "",
          month: "",
          day: "",
          color: "white",
          background: "#99CAEB"
        };
      }
      style_tem.year = style_year;
      style_tem.month = style_month;
      style_tem.day = style_day;
      style.push(style_tem);
    }
    start_time = String(start_time).replace(/,/g, "-");
    end_time = String(end_time).replace(/,/g, "-");

    this.setData({
      style: style,
      start_time: start_time,
      end_time: end_time
    });
  },
  confirm_time: function() {
    var start_time_string = this.data.start_time;
    var start_time = Date.parse(start_time_string);
    var start_time = new Date(start_time);
    var start_time = this.timetodata(start_time)


    var end_time_string = this.data.end_time;
    var end_time = Date.parse(end_time_string);
    var end_time = new Date(end_time);
    var end_time = this.timetodata(end_time)


    if (start_time == 'NaN月NaN日' && end_time == 'NaN月NaN日') {
      wx.showToast({
        title: "请选择日期",
        icon: 'none', // 'none'为无图标
        duration: 2000 //多少毫秒后消失
      });
    } else {
      if (start_time == 'NaN月NaN日') {
        var during = end_time
      }
      if (end_time == 'NaN月NaN日') {
        var during = start_time
      }
      if (start_time != 'NaN月NaN日' && end_time != 'NaN月NaN日') {
        var during = start_time + "-" + end_time;
      }

      var show_calendar = this.data.show_calendar
      show_calendar: !show_calendar

      this.setData({
        show_calendar: !show_calendar,
        'tour_info.during': during,
        start_time: start_time_string,
        end_time: end_time_string
      })
    }


  },
  timetodata: function(now) {
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return month + "月" + date + "日";
  },
})